package com.iqiyi.pps.epg.core.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.kiwi.utils.Configuration;
import com.iqiyi.pps.epg.core.model.carousel.AutoCarouselEpisodeLibrary;
import com.iqiyi.pps.epg.core.model.carousel.ProgramLegoData;
import com.iqiyi.pps.epg.core.model.carousel.ProgramQipuData;
import com.iqiyi.pps.epg.core.model.channel.SearchSettingConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by karkarrotxu on 2015/10/16.
 */
public final class ApiLegoUtil {
    private ApiLegoUtil() {
    }

    private static Logger logger = LoggerFactory.getLogger(ApiLegoUtil.class);
    public static final String LEGO_API_SEARCH_SEARCH_URL = Configuration.getString("lego.api.search.search.url");

    public static final String LEGO_API_SPORT_RELATION_URL = Configuration.getString("lego.api.sport.relation");

    public static Map<String, Object> BASE_FILTER_MAP = new HashMap<String, Object>();

    private static Map<String, AlbumLegoDataCache> albumCacheMap = new ConcurrentHashMap<>(512);
    private static long lastUpdateCache = System.currentTimeMillis();
    private static long refreshGap = 60000L;

    public static final int SPORT_ADD_RELATION = 1;
    public static final int SPORT_REMOVE_RELATION = 0;

    static {
        initBaseProgramFilter();

    }

    private static void initBaseProgramFilter() {
        //globalPublishDate asc
        // videoOrder asc
        //BASE_FILTER_MAP.put("page.orderBy", "videoOrder,globalPublishDate");
        // BASE_FILTER_MAP.put("page.orderBy", "globalPublishDate,videoOrder");
        // BASE_FILTER_MAP.put("page.order", "asc,asc");
        BASE_FILTER_MAP.put("filter_GTL_qipuId", "0");
        BASE_FILTER_MAP.put("t", "0");//类型节目

        //最小时间限制 60s
        BASE_FILTER_MAP.put("filter_GEL_duration", "60000");

        //正片
        BASE_FILTER_MAP.put("filter_EQI_contentType", "1");
//        //免费
//        BASE_FILTER_MAP.put("filter_INI_isPurchase", "0,-100");
//        //  BASE_FILTER_MAP.put("filter_EQI_freeType", "0");
//        //页面发布
//        BASE_FILTER_MAP.put("filter_EQI_pagePublishStatus", "1");
    }

    public static List<Long> collectValidProgram00(AlbumLegoData albumLegoData, SearchSettingConfig config) {
        if (config == null) {
            config = SettingConfigUtil.getInstance().getDefault();
        }
        if (albumLegoData.getAlbumId() < 1) {
            logger.info("[albumLegoData qipuId={}]", albumLegoData.getQipuId());
            return null;
        }
        Map<String, Object> params = SettingConfigUtil.getInstance().transBySearchConfig(config);
        long albumId = albumLegoData.getAlbumId();
        params.put("filter_EQL_albumId", "" + albumId);
        int pageNo = 1;
        params.putAll(BASE_FILTER_MAP);
        //album_source_type 对应 lego api数据中 orderType
        //orderType =0 时 根据 videoOrder 升序
        //orderType =1时 根据 globalPublishDate 升序
        if (albumLegoData.getOrderType() != null) {
            params.put("page.order", "asc");
            if (albumLegoData.getOrderType() == 0) {
                params.put("page.orderBy", "videoOrder");
            } else {
                params.put("page.orderBy", "globalPublishDate");
            }
        }
        JSONObject entity = null;
        JSONObject dataJSON = null;
        JSONArray resultArr = null;
        List<Long> children = new ArrayList<Long>(2000);
        int totalCount = 0;
        try {
            while (true) {
                params.put("page.pageNo", "" + pageNo);
                entity = ApiHttpRequestUtil.getMethod(LEGO_API_SEARCH_SEARCH_URL, params);
                if (null == entity) {
                    break;
                }
                dataJSON = entity.getJSONObject("data");
                resultArr = dataJSON.getJSONArray("result");
                if (totalCount == 0) {
                    totalCount = dataJSON.getIntValue("totalCount");
                }
                Iterator<Object> it = resultArr.iterator();
                while (it.hasNext()) {
                    children.add(((JSONObject) it.next()).getLongValue("qipuId"));
                }
                if (dataJSON.getBoolean("hasNext")) {
                    pageNo++;
                } else {
                    break;
                }
            }
            entity = null;
            albumLegoData.setChildrenNum(children.size());
            albumLegoData.setReadTotalCount(totalCount);
        } catch (Exception e) {
            logger.error("[collectValidProgram00] error [albumId={}] ", albumId);
            return new ArrayList<Long>();
        }
        return children;
    }

    public static List<Long> getEpisodeChildren(long qipuId, SearchSettingConfig config) {
        AlbumLegoData albumLegoData = queryAlbumId(qipuId);
        List<Long> children = collectValidProgram00(albumLegoData, config);
        return children;
    }

    public static void fillAlbumRelation(List<ProgramQipuData> qipuDatas) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("t", "0");

        for (ProgramQipuData tempData : qipuDatas) {
            logger.info("[fillAlbumRelation][query qipuId ]", tempData.getOriginal().getCarouselEpisode());
            params.put("filter_EQL_qipuId", "" + tempData.getOriginal().getCarouselEpisode());
            try {
                JSONObject data = ApiHttpRequestUtil.getMethod(LEGO_API_SEARCH_SEARCH_URL, params);
                if (data != null) {
                    JSONArray resultArr = data.getJSONObject("data").getJSONArray("result");
                    if (resultArr.size() > 0) {
                        JSONObject dataJSON = resultArr.getJSONObject(0);
                        if (dataJSON != null) {
                            tempData.setAlbumName(dataJSON.getString("albumDisplayName"));
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("[fillAlbumRelation][exception={}][carousel_episode={}]", e, tempData.getOriginal().getCarouselEpisode());
            }
        }
    }

    public static List<ProgramLegoData> queryByQipuIds(List<Long> qipuIdList) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("t", "0");//类型专辑
        params.put("filter_INL_qipuId", qipuIdList.toString().replaceAll("\\[|\\]|\\s", ""));
        JSONObject entity = null;
        JSONObject dataJSON = null;
        JSONArray resultArr = null;
        List<ProgramLegoData> children = new ArrayList<ProgramLegoData>(50);
        ProgramLegoData temp = null;
        int pageNo = 1;
        try {
            while (true) {
                params.put("page.pageNo", "" + pageNo);
                entity = ApiHttpRequestUtil.getMethod(LEGO_API_SEARCH_SEARCH_URL, params);
                if (null == entity) {
                    break;
                }
                dataJSON = entity.getJSONObject("data");
                resultArr = dataJSON.getJSONArray("result");
                Iterator<Object> it = resultArr.iterator();
                while (it.hasNext()) {
                    temp = makeUpToProgramLegoData((JSONObject) it.next());
                    if (temp != null) {
                        children.add(temp);
                    }
                }
                if (dataJSON.getBoolean("hasNext")) {
                    pageNo++;
                } else {
                    break;
                }
            }
        } catch (Exception e) {
            logger.error("[queryByQipuIds] error [params={}] ", params);
        }
        return children;
    }

    private static ProgramLegoData makeUpToProgramLegoData(JSONObject data) {
        ProgramLegoData legoData = new ProgramLegoData();
        AutoCarouselEpisodeLibrary autoCarouselEpisodeLibrary = legoData.getOriginal();
        try {
            autoCarouselEpisodeLibrary.setQipuId(data.getLongValue("qipuId"));
            autoCarouselEpisodeLibrary.setProgramName(rplaceNull(data.getString("displayName")));
            autoCarouselEpisodeLibrary.setAlbumId(data.getLongValue("albumId"));
            autoCarouselEpisodeLibrary.setAlbumName(rplaceNull(data.getString("albumDisplayName")));
            autoCarouselEpisodeLibrary.setChannelName(rplaceNull(data.getString("channelName")));
            autoCarouselEpisodeLibrary.setGlobalPublishDate(rplaceNull(data.getString("globalPublishDate")));
            autoCarouselEpisodeLibrary.setDuration(data.getLongValue("duration"));
            autoCarouselEpisodeLibrary.setCopyrightEndTime(formatCET(data.getString("copyrightEndTime")));
            autoCarouselEpisodeLibrary.setPagePublishStatus(rplaceNull(data.getString("pagePublishStatus")));
            autoCarouselEpisodeLibrary.setStatus(0);
            autoCarouselEpisodeLibrary.setCreatedTime(new Timestamp(System.currentTimeMillis()));

            autoCarouselEpisodeLibrary.setTwAlbumName(rplaceNull(data.getString("twAlbumDisplayName")));
            autoCarouselEpisodeLibrary.setTwChannelName(rplaceNull(data.getString("taiwanChannelName")));
            autoCarouselEpisodeLibrary.setTwProgramName(rplaceNull(data.getString("taiwanDisplayName")));
        } catch (Exception e) {
            logger.error("[data]" + data.toJSONString(), e);
            legoData.setIllegal(true);
        }
        return legoData;
    }

    private static String rplaceNull(String value) {
        return null == value ? "" : value;
    }

//    private static int formatPPS(String value) {
//        if (null == value || value.length() == 0) {
//            return 0;
//        }
//        return Long.valueOf(value);
//    }

    private static long formatCET(String value) {
        if (null == value || value.length() == 0) {
            return -100;
        }
        return Long.valueOf(value);
    }

    public static AlbumLegoData queryAlbumId(long qipuId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("t", "1");//类型专辑
        params.put("filter_EQL_qipuId", "" + qipuId);
        AlbumLegoData albumLegoData = new AlbumLegoData();
        albumLegoData.setQipuId(qipuId);
        JSONObject albumEntity = ApiHttpRequestUtil.getMethod(LEGO_API_SEARCH_SEARCH_URL, params);
        if (albumEntity == null) {
            logger.info("[ApiLegoUtil][queryAlbumId] 没有找到 lego数据,[qipuId={}]", qipuId);
            return albumLegoData;
        }
        JSONObject dataEntity = albumEntity.getJSONObject("data");
        if (dataEntity == null || dataEntity.getLong("totalCount") == null || dataEntity.getLong("totalCount") == 0) {
            logger.info("[ApiLegoUtil][queryAlbumId] lego数据不完整,[qipuId={}]", qipuId);
            return albumLegoData;
        }
        JSONArray resultArr = dataEntity.getJSONArray("result");
        if (resultArr.size() != 1) {
            return albumLegoData;
        }
        JSONObject entity = resultArr.getJSONObject(0);
        // orderType 对应 qipu album_source_type;
        Integer orderType = entity.getInteger("orderType");
        long albumId = entity.getLongValue("entityId");
        albumLegoData.setAlbumId(albumId);
        albumLegoData.setOrderType(orderType);
        return albumLegoData;
    }

    public static AlbumLegoDataCache getValidCache(String key) {
        long current = System.currentTimeMillis();
        AlbumLegoDataCache cache = null;
        synchronized (albumCacheMap) {
            if (current - lastUpdateCache > refreshGap) {
                lastUpdateCache = current;
                albumCacheMap.clear();
            }
            cache = albumCacheMap.get(key);
        }
        return cache;
    }

    public static void addLegoDataCache(String cacheKey, AlbumLegoData albumLegoData, List<Long> children) {
        if (children == null || children.size() < 10) {
            logger.info("[addLegoDataCache] add " + cacheKey);
            AlbumLegoDataCache cache = new AlbumLegoDataCache();
            cache.setChildren(children);
            cache.setAlbumLegoData(albumLegoData);
            cache.setKey(cacheKey);
            albumCacheMap.put(cache.getKey(), cache);
        } else {
            logger.info("[addLegoDataCache] ignore " + cacheKey);
        }
    }

    /*
    op  0:解绑 1;绑定
    epgType "PPC" "PGC"
    * */
    public static boolean updateSportRelation(int op, long matchId, long programQipuId, String programName) {
        Map<String, String> params = new HashMap<String, String>();
        if (matchId == 0) {
            logger.error("[error matchId is zero]");
            return false;
        }

        params.put("op", op + "");
        params.put("matchId", matchId + "");
        params.put("programName", programName);
        params.put("programQipuId", programQipuId + "");
        params.put("epgType", "PPC");
        JSONObject result = ApiHttpRequestUtil.getMethod(LEGO_API_SPORT_RELATION_URL, params);
        if (result != null && Constants.CODE_SUC.equals(result.getString("code"))) {
            return true;
        }
        return false;
    }
}




